package com.nxzh.de.executor.task;

import com.alibaba.fastjson2.JSONObject;
import com.nxzh.de.executor.common.constant.CacheConstants;
import com.nxzh.de.executor.service.impl.ReadInstructionsImpl;
import com.nxzh.de.executor.service.impl.SuckBackServiceImpl;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 炉台防倒吸监听任务
 */
@Component
public class SuckbackTask {
    private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private SuckBackServiceImpl suckBackService;

    @Resource
    private ReadInstructionsImpl readInstructions;

    /**
     * 炉台防倒吸炉压波动监控
     * 1、获取配置信息(工步对应偏差Torr->List 单系列时间间隔)
     * 工步名称  工步ID   炉压设定    瞬间波动
     * 2、判断工步及差值
     * 存一份差值大于范围的数据(先不推)
     * 3、推送人员配置(按系列)
     */
    @XxlJob("listenInSuckback")
    public void listenInSuckback() throws Exception {
        String modelName = "automatic-descending-crucible1";
        Object status = redisTemplate.opsForValue().get(CacheConstants.DE_SUCK_BACK_RUN_KEY + modelName + ":status");
        if (status != null) {
            logger.info("{}炉台防倒吸炉压波动监控模型当前任务正在执行,请勿重复执行", modelName);
            XxlJobHelper.log("{}炉台防倒吸炉压波动监控模型当前任务正在执行,请勿重复执行", modelName);
        } else {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            redisTemplate.opsForValue().set(CacheConstants.DE_SUCK_BACK_RUN_KEY + modelName + ":status", "1", 6, TimeUnit.SECONDS);
            suckBackService.preventHearthDX(modelName, "");
            stopWatch.stop();
            logger.info("{}炉台防倒吸炉压波动监控模型运行完成,耗时:{}秒", modelName, String.format("%.2f", stopWatch.getTotalTimeSeconds()));
            redisTemplate.delete(CacheConstants.DE_SUCK_BACK_RUN_KEY + modelName + ":status");
            XxlJobHelper.log("{}炉台防倒吸炉压波动监控模型运行完成,耗时:{}秒", modelName, String.format("%.2f", stopWatch.getTotalTimeSeconds()));
        }
    }

    @XxlJob("detest")
    public void detest() throws Exception {
        logger.info("上条数据：{}", redisTemplate.opsForValue().get(CacheConstants.DE_SUCK_BACK_KEY));
        JSONObject suckBackFromDE = readInstructions.findSuckBackFromDE("908");
        logger.info("本条数据：{}", suckBackFromDE.toJSONString());
    }
}
